package com.zr.d_c.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zr.d_c.model.User;
import com.zr.d_c.service.DishService;
import com.zr.d_c.service.SellerService;
import com.zr.d_c.serviceimpl.DishServiceImpl;
import com.zr.d_c.serviceimpl.SellerServiceImpl;
/**
 * 商家批量增加菜品
 * @author Administrator
 *
 */
public class InsertAllDishController extends HttpServlet {
	SellerService sellerService = new SellerServiceImpl();
	DishService dishService = new DishServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf8");
		resp.setCharacterEncoding("utf8");
		HttpSession session = req.getSession();
		PrintWriter pw = resp.getWriter();
		User u = (User) session.getAttribute("currentUser");
		int sid = sellerService.getSellerSidByUid(u.getUid());
		//1.得到FileItem的集合
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//设置上传最大大小
		upload.setSizeMax(1024 * 1024 * 5);
		upload.setHeaderEncoding("utf-8");
		List<FileItem> items;
		try {
			items = upload.parseRequest(req);
			//获得上传文件名
			String fileName = items.get(0).getName();
			StringBuffer path = new StringBuffer("c:/config/");
			File file = new File(path.toString());
			file.mkdirs();
			path.append(fileName);
			File filename = new File(path.toString());
			filename.createNewFile();
			InputStream in = items.get(0).getInputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			OutputStream out = new FileOutputStream(path.toString());
			while((len = in.read(buffer)) != -1){
				out.write(buffer, 0, len);
			}
			out.close();
			in.close();
			if(dishService.insertAllDish(path.toString(), sid)){
				pw.write("1");
			}else{
				pw.write("0");
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
